package com.ssyx.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

public class JwtHelper {
	
	private static final long TOKEN_TIME_EXPIRATION = 365L * 24 * 60 * 60 * 1000;
	private static final String TOKEN_SIGN_KEY = "ssyx";
	
	// 根据userId+userName生成token字符串
	public static String createToken(Long id, String name) {
		return Jwts.builder()
				.setSubject("SSYX-INFO")
				.setExpiration(new Date(System.currentTimeMillis() + TOKEN_TIME_EXPIRATION))
				.claim("id", id)
				.claim("name", name)
				.signWith(SignatureAlgorithm.HS512, TOKEN_SIGN_KEY)
				.compressWith(CompressionCodecs.GZIP)
				.compact();
	}
	
	public static Long getId(String token) {
		if (StringUtils.isEmpty(token)) return null;
		Jws<Claims> claimsJws = Jwts.parser().setSigningKey(TOKEN_SIGN_KEY).parseClaimsJws(token);
		Claims claims = claimsJws.getBody();
		Integer userId = (Integer) claims.get("id");
		return userId.longValue();
	}
	
	public static String getName(String token) {
		if (StringUtils.isEmpty(token)) return "";
		Jws<Claims> claimsJws = Jwts.parser().setSigningKey(TOKEN_SIGN_KEY).parseClaimsJws(token);
		Claims claims = claimsJws.getBody();
		return (String) claims.get("name");
	}
	
	public static void main(String[] args) {
		String token = JwtHelper.createToken(1L, "admin");
		System.out.println(token);
		System.out.println(JwtHelper.getId(token));
		System.out.println(JwtHelper.getName(token));
	}
}
